package com.yxt.common.sys;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.provider.Settings.Secure;

import com.yxt.model.Division;
import com.yxt.model.Function;
import com.yxt.model.Model;
import com.yxt.model.Valley;

public class CommUtil {
	
	/**
	 * 获取功能列表
	 * @param context
	 * @return
	 */
	public static Map<String,Function> getAppFunction(Context context){
		Map<String,Function> functions = new TreeMap<String,Function>();
		DocumentBuilderFactory  factory = DocumentBuilderFactory .newInstance();
		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.parse(context.getAssets().open(CommConstant.Config.FUNCTION_XML_LOCATION));
			Element root = document.getDocumentElement();
			NodeList nodes = root.getElementsByTagName(CommConstant.Function.NODE_FUNCTION);			
			for(int i=0;i<nodes.getLength();i++){
				Element funEle=(Element)nodes.item(i);
				Function function = new Function();
				String id = funEle.getAttribute(CommConstant.Function.NODE_FUNCTION_ID);
				function.setFuncid(id);
				Element eleId = (Element)funEle.getElementsByTagName(CommConstant.Function.NODE_FUNCTION_ICO).item(0);
				function.setIco(eleId.getFirstChild().getNodeValue());
				Element eleName = (Element)funEle.getElementsByTagName(CommConstant.Function.NODE_FUNCTION_NAME).item(0);
				function.setName(eleName.getFirstChild().getNodeValue());
				Element eleUrl = (Element)funEle.getElementsByTagName(CommConstant.Function.NODE_FUNCTION_CLS).item(0);
				function.setUrl(eleUrl.getFirstChild().getNodeValue());
				functions.put(id, function);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}		
		return functions;
	}
	
	/**
	 * 获取机器唯一编码,此代码只在真机有用
	 * @param context
	 * @return
	 */
	public static String getMachineId(Context context){
		String machineId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
		return machineId;
	}
	
	/**
	 * 转换经纬度
	 * @param inputStr
	 * @return
	 */
	public static int getGisDegree(String inputStr){
		double ret = Double.parseDouble(inputStr);
		if(ret >= 360){
			String du;
			String fen;
			String miao;
			miao = inputStr.substring(inputStr.length()-2, inputStr.length());
			fen = inputStr.substring(inputStr.length()-4, inputStr.length()-2);
			du = inputStr.substring(0, inputStr.length()-4);
			ret = Double.parseDouble(du) + Double.parseDouble(fen)/60 + Double.parseDouble(miao)/3600;
		}
		return (int)(ret* 1E6);
	}
	
	/**
	 * 获取区域SQL
	 * @return
	 */
	public static String getDefaultAreaSql() {
		StringBuffer areaSql = new StringBuffer();
		Map<String,String> template = CommConstant.Main.TEMPLATES.get(CommConstant.Main.CURRENT_TEMPLATE_CODE);
		Map<String, String> function = CommConstant.Main.FUNCTIONS.get(CommConstant.Main.CURRENT_TEMPLATE_CODE).get("WATER");		
		String parameters = function.get("parameters");		
		if (StringUtil.isEmpty(parameters) || parameters.indexOf(CommConstant.Config.DEFAULT_AREA_PLACEHOLDER) == -1) {
			areaSql.append("code = '" + template.get("rootarea").substring(0,2) + "'");
		} else {
			String[] array = parameters.split(CommConstant.Config.DEFAULT_ITEM_SPLITOR);
			String s  = "";
			for (int i = 0; i < array.length; i++) {
				if (array[i].indexOf(CommConstant.Config.DEFAULT_AREA_PLACEHOLDER) > -1) {
					s = array[i].substring(CommConstant.Config.DEFAULT_AREA_PLACEHOLDER.length());
					break;
				}
			}
			if (StringUtil.isEmpty(s)) {
				s = "type = '"+CommConstant.Rain.PROVINCE_TYPE+"'";
			}
			areaSql.append(s);
		}
		return areaSql.toString();
	}
	
	/**
	 * 获取流域SQL
	 * @param type
	 * @return
	 */
	public static String getDefaultRiverSql(int type) {
		StringBuffer riverSql = new StringBuffer();
		Map<String,String> template = CommConstant.Main.TEMPLATES.get(CommConstant.Main.CURRENT_TEMPLATE_CODE);
		Map<String, String> function = CommConstant.Main.FUNCTIONS.get(CommConstant.Main.CURRENT_TEMPLATE_CODE).get("WATER");		
		String parameters = function.get("parameters");
		if (StringUtil.isEmpty(parameters) || parameters.indexOf(CommConstant.Config.DEFAULT_MAINRIVER_PLACEHOLDER) == -1) {
			if (StringUtil.isEmpty(template.get("rootriver"))) {
				riverSql.append("type = '"+CommConstant.Water.MAIN_TYPE+"'");
			} else {
				riverSql.append("code ='" + template.get("rootriver") + "'");
			}
		} else {
			String[] array = parameters.split(CommConstant.Config.DEFAULT_ITEM_SPLITOR);
			String s  = "";
			if (CommConstant.Water.DEFAULT_MAIN_RIVER == type) {
				for (int i = 0; i < array.length; i++) {
					if (array[i].indexOf(CommConstant.Config.DEFAULT_MAINRIVER_PLACEHOLDER) > -1) {
						s = "(" + array[i].substring(CommConstant.Config.DEFAULT_MAINRIVER_PLACEHOLDER.length()) + ")";
						break;
					}
				}
				if (StringUtil.isEmpty(s)) {
					s = "type = '"+CommConstant.Water.MAIN_TYPE+"'";
				}
				riverSql.append(s);
			} else {
				for (int i = 0; i < array.length; i++) {
					if (array[i].indexOf(CommConstant.Config.DEFAULT_SUBRIVER_PLACEHOLDER) > -1) {
						s = "(" + array[i].substring(CommConstant.Config.DEFAULT_SUBRIVER_PLACEHOLDER.length()) + ")";
						break;
					}
				}
				if (StringUtil.isEmpty(s)) {
					s = "type = '"+CommConstant.Water.SUB_TYPE+"'";
				}
				riverSql.append(s);
			}
		}
		return riverSql.toString();
	}
	
	public static int getGisDegree(float degree){
		return getGisDegree(String.valueOf(degree));
	}
	
	/**
	 * 获取相关区域的下标（初始化用）
	 * @param divisions
	 * @param code
	 * @param type
	 * @return
	 */
	public static int getCurrentRegionIndex(List<Division> divisions,String code,int type) {
		int index = 0;
		if (divisions == null || divisions.size() == 0)
			return index;
		switch(code.length()) {
			case CommConstant.Main.DEFAULT_PROVINCE_TYPE:
				code = code.substring(0,CommConstant.Main.DEFAULT_PROVINCE_TYPE);
				break;
			case CommConstant.Main.DEFAULT_CITY_TYPE:
				code = code.substring(0,CommConstant.Main.DEFAULT_CITY_TYPE);
				break;
			case CommConstant.Main.DEFAULT_COUNTY_TYPE:
				break;
		} 
		for (int i = 0; i < divisions.size(); i++) {
			if (divisions.get(i).getCode().equals(code)) {
				index = i; 
				break;
			}
		}
		return index;
	}

	/**
	 * 获取相关流域的下标（初始化用）
	 * @param divisions
	 * @param code
	 * @param type
	 * @return
	 */
	public static int getCurrentRiverIndex(List<Valley> rivers,String code,int type) {
		int index = 0;
		if (rivers == null || rivers.size() == 0)
			return index;
		switch(code.length()) {
			case CommConstant.Main.DEFAULT_SUB_TYPE:
				code = code.substring(0,CommConstant.Main.DEFAULT_SUB_TYPE);
				break;
			case CommConstant.Main.DEFAULT_MAIN_TYPE:
				break;
		} 
		for (int i = 0; i < rivers.size(); i++) {
			if (rivers.get(i).getCode().equals(code)) {
				index = i; 
				break;
			}
		}
		return index;
	}

	/**
	 * 获取相关模板的下标（初始化用）
	 * @param divisions
	 * @param code
	 * @param type
	 * @return
	 */
	public static int getCurrentTemplateIndex(List<Model> templtes,String code) {
		int index = 0;
		if (templtes == null || templtes.size() == 0)
			return index;
		for (int i = 0; i < templtes.size(); i++) {
			if (templtes.get(i).getCode().equals(code)) {
				index = i; 
				break;
			}
		}
		return index;
	}

	/**
	 * 保存模板信息
	 * @param context
	 */
	public static void persistenceAutoLogin(Context context) {
		SharedPreferences settings = context.getSharedPreferences(CommConstant.Login.APP_KEY, Context.MODE_PRIVATE);
		Editor editor = settings.edit();
		editor.putString(CommConstant.Login.APP_AUTO_LOGIN, "");
		editor.commit();
	}

	/**
	 * 保存模板信息
	 * @param context
	 */
	public static void persistenceTemplateInfo(Context context) {
		SharedPreferences settings = context.getSharedPreferences(CommConstant.Login.APP_KEY, Context.MODE_PRIVATE);
		Editor editor = settings.edit();
		editor.putString(CommConstant.Login.APP_TEMPLATE_CODE, CommConstant.Main.CURRENT_TEMPLATE_CODE);
		editor.putString(CommConstant.Login.APP_TEMPLATE_NAME, CommConstant.Main.CURRENT_TEMPLATE_NAME);
		editor.commit();
	}
	
	/**
	 * 保存区域信息
	 * @param context
	 */
	public static void persistenceAreaInfo(Context context) {
		SharedPreferences settings = context.getSharedPreferences(CommConstant.Login.APP_KEY, Context.MODE_PRIVATE);
		Editor editor = settings.edit();
		editor.putString(CommConstant.Login.APP_AREA_CODE, CommConstant.Main.CURRENT_AREA_CODE);
		editor.putString(CommConstant.Login.APP_AREA_NAME, CommConstant.Main.CURRENT_AREA_NAME);
		editor.commit();
	}
	
	/**
	 * 保存流域信息
	 * @param context
	 */
	public static void persistenceRiverInfo(Context context) {
		SharedPreferences settings = context.getSharedPreferences(CommConstant.Login.APP_KEY, Context.MODE_PRIVATE);
		Editor editor = settings.edit();
		editor.putString(CommConstant.Login.APP_RIVER_CODE, CommConstant.Main.CURRENT_RIVER_CODE);
		editor.putString(CommConstant.Login.APP_RIVER_NAME, CommConstant.Main.CURRENT_RIVER_NAME);
		editor.commit();
	}
	
	/**
	 * 获取颜色
	 * @param fs
	 * @return
	 */
	public static int getColor(String fs) {
		float flfs = Float.parseFloat(fs);
		int color = 0;
		if(flfs>=51.0f)
			color = Color.argb(1, 255, 0, 0);
		else if(flfs>=41.5f && flfs <51.0f)
			color = Color.argb(1, 255, 0, 255);
		else if(flfs>=32.7f && flfs <41.5f)
			color = Color.argb(1, 255, 128, 0); 
		else if(flfs>=24.5f && flfs <32.7f)
			color = Color.argb(1, 255, 255, 0);
		else if(flfs>=17.2f && flfs <24.5f)
			color = Color.argb(1, 0, 255, 0	);
		else
			color = Color.argb(1, 0, 0, 255);
		return color;
	}
}
